package com.szholly.plug.form.directive;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Component;

import com.szholly.utils.freemarker.directive.DirectiveUtils;
import com.szholly.utils.freemarker.directive.IDirective;
import com.szholly.utils.spring.springmvc.route.FunctionInfo;
import com.szholly.utils.util.TreeDataNode;
import com.szholly.data.cache.DomainCache;
import com.szholly.data.general.CachedTableDomain;
import com.szholly.data.general.IDomain;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 定义所有字典项名称的数据标签 并按字典域名称排序
 */
@Component("directive_domainname")
public class DomainNameDirective implements TemplateDirectiveModel, IDirective {

	/**
	 * 是否显示不可写域
	 */
	private static String PARA_SHOWISREADONLY = "showIsReadonly";

	@Override
	public FunctionInfo getFunctionInfo() {
		String paraInfo = "tableName：数据字典表名 <br/>domainName：字典域名称(可为空)<br/>addSpaceItem：是否添加空行(true,false)"
				+ "调用示例：<br/>"
				+ "<Combobox <br/>"
				+ "data=<@domainname showIsReadonly='true'>${data}</@domain> <br/>"
				+ "/><br/>";
		FunctionInfo info = new FunctionInfo("domainname", 1, "表单",
				"获取所有字典项名称数据(json字符串)", paraInfo);
		return info;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void execute(Environment env, Map params, TemplateModel[] model,
			TemplateDirectiveBody body) throws TemplateException, IOException {

		Boolean showIsReadonly = DirectiveUtils.getBool(PARA_SHOWISREADONLY,
				params);

		HashMap<String, IDomain> domainCache = DomainCache.getDomainCache();
		Set<String> keys = domainCache.keySet();

		List<TreeDataNode> resultList = new ArrayList<TreeDataNode>();
		List<IDomain> domainList = new ArrayList<IDomain>();

		for (String key : keys) {
			IDomain pTable = domainCache.get(key);
			if (pTable == null) {
				continue;
			}

			if (!pTable.getIsManageCodeTable() && !showIsReadonly) {
				continue;
			}

			if (domainList.contains(pTable)) {
				continue;
			}
			domainList.add(pTable);

			TreeDataNode item = new TreeDataNode();
			item.setid(key);
			item.setText(pTable.getDomainAliasName());
			
			// 缓存的字典为可编辑字典
			if(pTable instanceof CachedTableDomain){
				item.setAttributes(true);
			}else{
				item.setAttributes(false);
			}
			item.setState("open");
			resultList.add(item);
		}

		Collections.sort(resultList, new ComparatorUser());

		JSONArray arrayObject = JSONArray.fromObject(resultList);
		String returnValue = arrayObject.toString();

		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(
				params);
		paramWrap.put("data", DEFAULT_WRAPPER.wrap(returnValue));
		Map<String, TemplateModel> origMap = DirectiveUtils
				.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}

	public class ComparatorUser implements Comparator<TreeDataNode> {

		public int compare(TreeDataNode arg0, TreeDataNode arg1) {
			return arg0.getText().compareTo(arg1.getText());
		}
	}
}
